<?php

namespace app\api\controller\v2;

use addons\epay\library\Service;
use app\admin\model\BillModel;
use app\common\controller\Api;
use app\common\controller\Wxpay;
use app\common\model\Contract as ThisModel;
use app\common\model\ContractError;
use app\common\model\Message;
use app\common\model\OrderPaymentRecords;
use app\common\model\PaymentRecords;
use app\common\model\User;
use think\Db;
use think\Env;
use think\Exception;

/**
 * 合同接口
 */
class Contract extends Api
{
    protected $noNeedLogin = ['getType'];
    protected $noNeedRight = '*';

    /**
     * @brief   添加合同
     * @author wanchengniuniu
     * @date 2025/2/27
     *
     * @param
     * @return
     */
    public function add()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $homeowner_id=$user->id;
        $homeowner_phone=$user->mobile;
        $keys=$this->get_keys('add'.$homeowner_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }

        $validate=new \app\api\validate\v2\Contract();
        $check_result=$validate->scene('add')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        //检测房子
        $house_info=Db::name('house')->where(['id'=>$getData['house_id']])->find();
        if(!$house_info){
            $this->error('获取房源失败');
        }
        if($house_info['status']!=1){
            if($house_info['status']==-1){
                $this->error('房源未审核通过');
            }
            if($house_info['status']==2){
                $this->error('房源已下架');
            }
            $this->error('房源状态异常');
        }
        $room_info=Db::name('building_room')->where(['id'=>$house_info['room_id']])->find();
        if(!$room_info){
            $this->error('获房间失败');
        }
        if($room_info['status']==3){
            $this->error('房间状态异常');
        }
        $build_info=Db::name('building')->where(['id'=>$room_info['build_id']])->find();
        if(!$build_info){
            $this->error('获楼栋失败');
        }
        //检测房东是否认证
        $homeowner_re=Db::name('house_owner')->where(['user_id'=>$house_info['user_id']])->find();
        if(!$homeowner_re){
            $this->error('获房东认证信息失败');
        }
        if($homeowner_re['status']!=1){
            $this->error('房东认证信息状态异常');
        }
        $homeowner_info=[
            'homeowner_name'=>$homeowner_re['real_name'],
            'homeowner_idcard'=>$homeowner_re['card_no'],
            'house_address'=>$house_info['address'],
            'homeowner_phone'=>$homeowner_phone,
        ];
        if(date('Y-m-d',strtotime($getData['start_time']))!=$getData['start_time']){
            $this->del_rekey($keys);
            $this->error('开始时间格式错误');
        }
        if(date('Y-m-d',strtotime($getData['end_time']))!=$getData['end_time']){
            $this->del_rekey($keys);
            $this->error('结束时间格式错误');
        }
//        if (!empty($getData['attachment'])) {
//            $photos=explode(',',$getData['attachment']);
//            foreach ($photos as $v){
//                $ext_arr=explode('.',$v);
//                if(!in_array($ext_arr[count($ext_arr)-1],['pdf'])){
//                    $this->del_rekey($keys);
//                    $this->error('附件格式错误');
//                }
//                $this_data=['attachment'=>$v];
//                $check_result=$validate->scene('add_attachment')->check($this_data);
//                if (!$check_result) {
//                    $this->del_rekey($keys);
//                    $this->error($validate->getError());
//                }
//            }
//        }
        if (!empty($getData['photo'])) {
            $photos=explode(',',$getData['photo']);
            foreach ($photos as $v){
                $ext_arr=explode('.',$v);
                if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg'])){
                    $this->del_rekey($keys);
                    $this->error('图片格式错误');
                }
                $this_data=['photo'=>$v];
                $check_result=$validate->scene('add_photo')->check($this_data);
                if (!$check_result) {
                    $this->del_rekey($keys);
                    $this->error($validate->getError());
                }
            }
        }
//        $user_info=User::where(['id'=>$getData['user_id']])->find();
        $user_info=User::where(['mobile'=>$getData['user_phone']])->find();
        if(!$user_info){
            $this->del_rekey($keys);
            $this->error('用户未注册');
        }
        if($user_info['id']==$homeowner_id){
            $this->del_rekey($keys);
            $this->error('不能与自己签合同');
        }
        $getData['user_id']=$user_info['id'];
        $insert_data=[
            'homeowner_id'=>$homeowner_id,
            'homeowner_name'=>$homeowner_info['homeowner_name'],
            'homeowner_idcard'=>$homeowner_info['homeowner_idcard'],
            'homeowner_phone'=>$homeowner_info['homeowner_phone'],
            'house_address'=>$homeowner_info['house_address'],
            'type'=>$getData['type'],
            'user_id'=>$user_info['id'],
            'house_id'=>$getData['house_id'],
            'start_time'=>$getData['start_time'],
            'end_time'=>strtotime($getData['end_time']),
            'money_zu'=>$getData['money_zu'],
            'money_ya'=>$getData['money_ya'],
            'ya_type'=>$getData['ya_type'],
            'water_num'=>$getData['water_num'],
            'electricity_num'=>$getData['electricity_num'],
            'pay_time'=>$getData['pay_time'],
            'money_electricity'=>$getData['money_electricity'],
            'money_water'=>$getData['money_water'],
//            'attachment'=>$getData['attachment'],
            'photo'=>$getData['photo'],
            'status'=>ThisModel::STATUS_NORMAL,
        ];
        //检测该房源是否有生效的合同
        $contract_info=ThisModel::where(['homeowner_id'=>$insert_data['homeowner_id'],'house_id'=>$insert_data['house_id'],'status'=>$insert_data['status']])->find();
        if($contract_info){
            $this->error('房源已签约');
        }
        $user_name=$user_info['username'];
        $insert_data['name']=$insert_data['homeowner_name'].'与'.$user_name;
        $insert_data['room_id']=$house_info['room_id'];
        $insert_data['user_name']=$getData['user_name'];
        $insert_data['user_card']=$getData['user_card'];
        $insert_data['user_phone']=$getData['user_phone'];
        $insert_data['build_id']=$room_info['build_id'];
        $insert_data['build_address']=$build_info['address'];
        $insert_data['room_name']=$room_info['name'];
        $insert_data['now_count']=0;
        $insert_data['moon_fang_data']=$moon_fang_data=date('Y-m-d',strtotime(date('Y-m')));
        ;
        //php71 think crud -t user_contract --relation=user --relation=user --relation=building --relation=building_room --relation=house --relationforeignkey=user_id --relationforeignkey=homeowner_id --relationforeignkey=build_id --relationforeignkey=room_id --relationforeignkey=house_id --imagefield=photo --filefield=attachment
        //php71 think crud -t user_contract -d 1
        //检测重复
        if(ThisModel::where($insert_data)->find()){
            $this->del_rekey($keys);
            $this->error('重复提交');
        }
        $insert_data['createtime']=time();
        $message_data=[
            'type'=>Message::TYPE_TWO,
            'user_id'=>$insert_data['user_id'],
            'title'=>'您的合同已签订',
            'content'=>'您的合同内容',
        ];
        $res=false;
        try{
            Db::startTrans();
            //推送缴费消息
            $id=(new ThisModel())->insertGetId($insert_data);
            $message_data['other_id']=$id;
            $re=Message::add($message_data);
            //修改房屋状态
            $re1=Db::name('house')->where(['id'=>$house_info['id']])->update(['status'=>2,'is_finish'=>1]);
            $re2=Db::name('building_room')->where(['id'=>$house_info['room_id']])->update(['status'=>3]);
            if($id && $re &&$re1 &&$re2){
                $res=true;
                Db::commit();
            }
            else{
                Db::rollback();
            }
        } catch (\DomainException $e) {
            Db::rollback();
        }
        if(!$res){
            $this->del_rekey($keys);
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }

    /**
     * @brief   获取合同押金方式
     * @author wanchengniuniu
     * @date 2025/2/26
     *
     * @param
     * @return
     */
    public function getYaTypeList()
    {
        $list=ThisModel::getYaTypeList();
        $this->success('获取成功',$list);
    }

    /**
     * @brief   获取合同列表(房东)
     * @author wanchengniuniu
     * @date 2025/2/27
     *
     * @param
     * @return
     */
    public function contractLists(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $page=isset($getData['page']) && !empty((int)$getData['page'])?(int)$getData['page']:1;
            $limit=isset($getData['limit']) && !empty((int)$getData['limit'])?(int)$getData['limit']:10;
            $type=(string)1;
            $where = ['c.status'=>$type,'c.homeowner_id'=>$user_id];
//            $where = ['c.status'=>$type];
            $Data = ThisModel::alias('c')
                ->join('building b','b.id=build_id')
                ->join('house h','h.id=house_id')
                ->field('c.house_id,c.house_address,c.start_time,c.end_time,c.money_zu,c.money_ya,c.homeowner_name,c.homeowner_phone,c.id,c.status,c.createtime,c.room_name,b.images as build_images,h.images as house_images')
                ->where($where)
                ->page($page,$limit)
                ->order('status asc,updatetime desc')
                ->select();
            foreach ($Data as $k=>$item){
                $item['status_text']=ThisModel::getStatusList(1,$item['status']);
                $item['createtime']=date('Y-m-d H:i',$item['createtime']);
                $item['end_time']=date('Y-m-d H:i',$item['end_time']);
//                $item['house_images']=get_all_img_path($item['house_images']);
                $item['house_images']=!empty($item['house_images'])?get_all_img_paths($item['house_images']):[];
                $item['build_images']=!empty($item['build_images'])?get_all_img_paths($item['build_images']):[];
                $Data[$k]=$item;
            }
            $this->success('查询成功',$Data);
        }else{
            $this->error('请求参数有误');
        }
    }


    /**
     * @brief   获取合同详情(房东)
     * @author wanchengniuniu
     * @date 2025/2/27
     */
    public function contractInfo()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id/d');
            if (!$id) {
                $this->error('参数错误');
            }

            $where = [
                'c.id' => $id,
                'c.status' => 1,
//              'c.homeowner_id'=>$user_id

            ];

            $item = ThisModel::alias('c')
                ->join('building b', 'b.id=build_id','left')
                ->join('house h', 'h.id=house_id','left')
                ->field('c.house_id,c.house_address,c.start_time,c.end_time,c.money_zu,c.money_ya,c.homeowner_name,c.homeowner_phone,c.id,c.status,c.createtime,c.room_name,photo,attachment,ya_type,b.images as build_images,h.images as house_images')
                ->where($where)->find();
            if (!$item) {
                $this->error('获取失败');
            }
            $item['status_text'] = ThisModel::getStatusList(1, $item['status']);
            $item['createtime'] = date('Y-m-d', $item['createtime']);
            $item['end_time'] = date('Y-m-d', $item['end_time']);
            $item['photo'] = get_all_img_path($item['photo']);
            $item['ya_type_text'] = ThisModel::getYaTypeList(1, $item['ya_type']);
            $item['attachment'] = get_all_img_path($item['attachment']);
            $item['house_images'] = !empty($item['house_images']) ? get_all_img_paths($item['house_images']) : [];
            $item['build_images'] = !empty($item['build_images']) ? get_all_img_paths($item['build_images']) : [];
            $this->success('查询成功', $item);
        } else {
            $this->error('请求参数有误');
        }
    }
    /**
     * @brief   获取合同列表(用户)
     * @author wanchengniuniu
     * @date 2025/2/27
     */
    public function contractUserLists()
    {
        if ($this->request->isPost()) {

            $user_id = $this->auth->id;

            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 10);

            $where = [
                'c.status' => 1,
                'c.user_id' => $user_id
            ];
            $Data = ThisModel::alias('c')
                ->join('building b', 'b.id=build_id', 'left')
                ->join('house h', 'h.id=house_id', 'left')
                ->field('c.house_id,c.room_id,c.house_address,c.start_time,c.end_time,c.money_zu,c.money_ya,c.homeowner_name,c.homeowner_phone,c.id,c.status,c.createtime,c.photo,c.room_name,b.images as build_images,h.images as house_images')
                ->where($where)
                ->page($page, $limit)
                ->order('c.status asc,updatetime desc')
                ->select();
            foreach ($Data as $k => $item) {
                $item['status_text'] = ThisModel::getStatusList(1, $item['status']);
                $item['createtime'] = date('Y-m-d H:i', $item['createtime']);
                $item['photo'] = get_all_img_path($item['photo']);
//                $item['attachment']=get_all_img_path($item['attachment']);
//                $item['house_images']=get_all_img_path($item['house_images']);
//                $item['build_images']=get_all_img_path($item['build_images']);
                $item['house_images'] = !empty($item['house_images']) ? get_all_img_paths($item['house_images']) : [];
                $item['build_images'] = !empty($item['build_images']) ? get_all_img_paths($item['build_images']) : [];
                $Data[$k] = $item;
            }
            $this->success('查询成功', $Data);
        } else {
            $this->error('请求参数有误');
        }
    }

    /**
     * @brief   获取合同详情(用户)
     * @author wanchengniuniu
     * @date 2025/2/27
     */
    public function contractUserInfo()
    {
        if ($this->request->isPost()) {

            $id = $this->request->param('id/d');
            if (!$id) {
                $this->error('参数错误');
            }

            $where = [
                'c.status' => 1,
                'c.id' => $id
            ];
            $item = ThisModel::alias('c')
                ->join('building b', 'b.id=build_id', 'left')
                ->join('house h', 'h.id=house_id', 'left')
                ->field('c.house_address,c.start_time,c.end_time,c.money_zu,c.money_ya,c.homeowner_name,
                c.homeowner_phone,c.id,c.status,c.createtime,c.room_name,photo,attachment,ya_type,c.user_sign_img,
                b.images as build_images,b.name as build_name,h.images as house_images')
                ->where($where)
                ->find();
            if (!$item) {
                $this->error('获取失败');
            }
            $item['status_text'] = ThisModel::getStatusList(1, $item['status']);
            $item['photo'] = get_all_img_path($item['photo']);
            $item['ya_type_text'] = ThisModel::getYaTypeList(1, $item['ya_type']);
            $item['attachment'] = get_all_img_path($item['attachment']);
            $item['createtime'] = date('Y-m-d H:i', $item['createtime']);
            $item['house_images'] = !empty($item['house_images']) ? get_all_img_paths($item['house_images']) : [];
            $item['build_images'] = !empty($item['build_images']) ? get_all_img_paths($item['build_images']) : [];
            $this->success('查询成功', $item);
        } else {
            $this->error('请求参数有误');
        }
    }

    /**
     * @brief   获取上次抄表
     * @author wanchengniuniu
     * @date 2025/2/27
     *
     * @param
     * @return
     */
    public function biaoInfo()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $homeowner_id=$user->id;
        $keys=$this->get_keys('biaoInfo'.$homeowner_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
        $validate=new \app\api\validate\v2\Contract();
        $check_result=$validate->scene('biaoInfo')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        //检测合同是否有效
        $where=['house_id'=>$getData['house_id'],
            'homeowner_id'=>$homeowner_id,
            'status'=>ThisModel::STATUS_NORMAL];
        $info=ThisModel::where($where)->find();
        if(!$info){
            $this->del_rekey($keys);
            $this->error('获取合同信息失败');
        }
        if($info['status']!=ThisModel::STATUS_NORMAL){
            $this->del_rekey($keys);
            $this->error('合同状态异常');
        }
        //检测是否有缴费记录
        $where1=['house_id'=>$getData['house_id']
//            ,'homeowner_id'=>$homeowner_id
        ];
        $log_info=PaymentRecords::where($where1)->find();
        if(!$log_info){
            $re_data=[
                'water'=>$info['water_num'],
                'electricity'=>$info['electricity_num'],
            ];
        }else{
            $re_data=[
                'water'=>$log_info['water_num'],
                'electricity'=>$log_info['electricity_num'],
            ];
        }
        $this->success('获取成功',$re_data);
    }

    /**
     * @brief   添加抄表
     * @author wanchengniuniu
     * @date 2025/2/27
     *
     * @param
     * @return
     */
    public function addBiao()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $other_data=json_decode(html_entity_decode($getData['other_data']),true);
        $homeowner_id=$user->id;
        $keys=$this->get_keys('addBiao'.$homeowner_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
        $validate=new \app\api\validate\v2\Contract();
        $check_result=$validate->scene('addBiao')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        //检测合同是否有效
        $info=ThisModel::where(['house_id'=>$getData['house_id'],'homeowner_id'=>$homeowner_id,'status'=>ThisModel::STATUS_NORMAL])->find();
        if(!$info){
            $this->del_rekey($keys);
            $this->error('获取合同信息失败');
        }
        if($info['status']!=ThisModel::STATUS_NORMAL){
            $this->del_rekey($keys);
            $this->error('合同状态异常');
        }

        if (!empty($getData['water_photo'])) {
            $photos=explode(',',$getData['water_photo']);
            foreach ($photos as $v){
                $ext_arr=explode('.',$v);
                if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg'])){
                    $this->del_rekey($keys);
                    $this->error('图片格式错误');
                }
                $this_data=['water_photo'=>$v];
                $check_result=$validate->scene('addBiao_water_photo')->check($this_data);
                if (!$check_result) {
                    $this->del_rekey($keys);
                    $this->error($validate->getError());
                }
            }
        }
        if (!empty($getData['electricity_photo'])) {
            $photos=explode(',',$getData['electricity_photo']);
            foreach ($photos as $v){
                $ext_arr=explode('.',$v);
                if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg'])){
                    $this->del_rekey($keys);
                    $this->error('图片格式错误');
                }
                $this_data=['electricity_photo'=>$v];
                $check_result=$validate->scene('addBiao_electricity_photo')->check($this_data);
                if (!$check_result) {
                    $this->del_rekey($keys);
                    $this->error($validate->getError());
                }
            }
        }
        $other_fee=0;
        foreach ($other_data as $v){
            $other_fee+=$v['money'];
        }
        $insert_data=[
            'homeowner_id'=>$homeowner_id,
            'contract_id'=>$info['id'],
            'user_id'=>$info['user_id'],
            'type'=>PaymentRecords::TYPE_OTHER,
            'water_photo'=>$getData['water_photo'],
            'electricity_photo'=>$getData['electricity_photo'],
            'other_fee'=>$other_fee,
            'other_data'=>json_encode($other_data),
            'water_num'=>$getData['water_num'],
            'status'=>PaymentRecords::STATUS_DEFAULT,
            'electricity_num'=>$getData['electricity_num'],
        ];
        //php71 think crud -t user_payment_records --relation=user --relation=user --relation=user_contract --relationforeignkey=user_id --relationforeignkey=homeowner_id --relationforeignkey=contract_id --imagefield=water_photo --imagefield=electricity_photo
        //php71 think crud -t user_payment_records -d 1
        //php71 think crud -t user_message --relation=user --relationforeignkey=user_id
        //检测重复

        if(PaymentRecords::where($insert_data)->find()){
            $this->del_rekey($keys);
            $this->error('重复提交');
        }
        //检测是否有缴费记录
        $log_info=PaymentRecords::where(['contract_id'=>$info['id'],'type'=>PaymentRecords::TYPE_OTHER])->order('id desc')->find();
        if(!$log_info){
            $re_data=[
                'water'=>$info['water_num'],
                'electricity'=>$info['electricity_num'],
            ];
        }
        else{
            $re_data=[
                'water'=>$log_info['water_num'],
                'electricity'=>$log_info['electricity_num'],
            ];
        }
        $insert_data['last_water_num']=$re_data['water'];
        $insert_data['last_electricity_num']=$re_data['electricity'];
        $this_water=bcsub($insert_data['water_num'],$insert_data['last_water_num'],2);
        $this_electricity=bcsub($insert_data['electricity_num'],$insert_data['last_electricity_num'],2);
        if($this_water<0){
            $this->del_rekey($keys);
            $this->error('水表参数异常');
        }
        if($this_electricity<0){
            $this->del_rekey($keys);
            $this->error('电表参数异常');
        }

        $money_electricity=bcmul($this_electricity,$info['money_electricity'],2);
        $money_water=bcmul($this_water,$info['money_water'],2);
        $money=bcadd($money_water,$money_electricity,2);
        $money=bcadd($money,$insert_data['other_fee'],2);
        $insert_data['money_electricity']=$money_electricity;
        $insert_data['money_water']=$money_water;
        $insert_data['money']=$money;
        $insert_data['createtime']=time();
        $insert_data['updatetime']=time();
//        $message_data=[
//            'type'=>Message::TYPE_ONE,
//            'user_id'=>$insert_data['user_id'],
//            'title'=>'您有一条待缴费消息',
//            'content'=>'您有一条待缴费内容',
//        ];
        $res=false;
        try{
            Db::startTrans();
            //推送缴费消息
            $id=(new PaymentRecords())->insertGetId($insert_data);
            //修改合同为已抄表
            $re1=ThisModel::where(['id'=>$insert_data['contract_id']])->update(['moon_chao_status'=>1]);
//            $message_data['other_id']=$id;
//            $re=Message::add($message_data);
//            if($id && $re && $re1){
            if($id && $re1){
                $res=true;
                Db::commit();
            }
            else{
                Db::rollback();
            }
        } catch (\DomainException $e) {
            Db::rollback();
        }
        if(!$res){
            $this->del_rekey($keys);
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }

    /**
     * @brief   一键抄表
     * @author wanchengniuniu
     * @date 2025/3/22
     *
     * @param
     * @return
     */
    public function addBiaoList()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();

        $homeowner_id=$user->id;
        $keys=$this->get_keys('addBiaoList'.$homeowner_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
        $validate=new \app\api\validate\v2\Contract();
        $check_result=$validate->scene('addBiaoList')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        $biao_data=json_decode(html_entity_decode($getData['biao_data']),true);
        $insert_data_all=[];
        $update_data_contract_ids=[];
        foreach ($biao_data as $getData){
            $check_result=$validate->scene('addBiao')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }

            //检测合同是否有效
            $info=ThisModel::where(['house_id'=>$getData['house_id'],'homeowner_id'=>$homeowner_id,'status'=>ThisModel::STATUS_NORMAL])->find();
            if(!$info){
                $this->del_rekey($keys);
                $this->error('获取合同信息失败');
            }

            if (!empty($getData['water_photo'])) {
                $photos=explode(',',$getData['water_photo']);
                foreach ($photos as $v){
                    $ext_arr=explode('.',$v);
                    if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg'])){
                        $this->del_rekey($keys);
                        $this->error('图片格式错误');
                    }
                    $this_data=['water_photo'=>$v];
                    $check_result=$validate->scene('addBiao_water_photo')->check($this_data);
                    if (!$check_result) {
                        $this->del_rekey($keys);
                        $this->error($validate->getError());
                    }
                }
            }
            if (!empty($getData['electricity_photo'])) {
                $photos=explode(',',$getData['electricity_photo']);
                foreach ($photos as $v){
                    $ext_arr=explode('.',$v);
                    if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg'])){
                        $this->del_rekey($keys);
                        $this->error('图片格式错误');
                    }
                    $this_data=['electricity_photo'=>$v];
                    $check_result=$validate->scene('addBiao_electricity_photo')->check($this_data);
                    if (!$check_result) {
                        $this->del_rekey($keys);
                        $this->error($validate->getError());
                    }
                }
            }
            $other_data=$getData['other_data'];
            $other_fee=0;
            foreach ($other_data as $vv){
                $other_fee+=$vv['money'];
            }
            $insert_data=[
                'homeowner_id'=>$homeowner_id,
                'contract_id'=>$info['id'],
                'user_id'=>$info['user_id'],
                'type'=>PaymentRecords::TYPE_OTHER,
                'status'=>PaymentRecords::STATUS_DEFAULT,
                'water_photo'=>$getData['water_photo'],
                'electricity_photo'=>$getData['electricity_photo'],
                'other_fee'=>$other_fee,
                'other_data'=>json_encode($other_data),
                'water_num'=>$getData['water_num'],
                'electricity_num'=>$getData['electricity_num'],
            ];
            //检测重复
            if(PaymentRecords::where($insert_data)->find()){
                $this->del_rekey($keys);
                $this->error('重复提交');
            }
            //检测是否有缴费记录
            $log_info=PaymentRecords::where(['contract_id'=>$info['id'],'type'=>PaymentRecords::TYPE_OTHER])->order('id desc')->find();
            if(!$log_info){
                $re_data=[
                    'water'=>$info['water_num'],
                    'electricity'=>$info['electricity_num'],
                ];
            }
            else{
                $re_data=[
                    'water'=>$log_info['water_num'],
                    'electricity'=>$log_info['electricity_num'],
                ];
            }
            $insert_data['last_water_num']=$re_data['water'];
            $insert_data['last_electricity_num']=$re_data['electricity'];
            $this_water=bcsub($insert_data['water_num'],$insert_data['last_water_num'],2);
            $this_electricity=bcsub($insert_data['electricity_num'],$insert_data['last_electricity_num'],2);
            if($this_water<0){
                $this->del_rekey($keys);
                $this->error('水表参数异常');
            }
            if($this_electricity<0){
                $this->del_rekey($keys);
                $this->error('电表参数异常');
            }
            $money_electricity=bcmul($this_electricity,$info['money_electricity'],2);
            $money_water=bcmul($this_water,$info['money_water'],2);
            $money=bcadd($money_water,$money_electricity,2);
            $money=bcadd($money,$insert_data['other_fee'],2);
            $insert_data['money_electricity']=$money_electricity;
            $insert_data['money_water']=$money_water;
            $insert_data['money']=$money;
            $insert_data['createtime']=time();
            $insert_data['updatetime']=time();
            $insert_data_all[]=$insert_data;
            $update_data_contract_ids[]=$insert_data['contract_id'];
        }

//        $message_data=[
//            'type'=>Message::TYPE_ONE,
//            'user_id'=>$insert_data['user_id'],
//            'title'=>'您有一条待缴费消息',
//            'content'=>'您有一条待缴费内容',
//        ];
        if(empty($insert_data_all)){
            $this->del_rekey($keys);
            $this->error('无提交项');
        }
        $res=false;
        try{
            Db::startTrans();
            //推送缴费消息
//            $id=(new PaymentRecords())->insertGetId($insert_data);
            $id=(new PaymentRecords())->insertAll($insert_data_all);
            //修改合同为已抄表
            $re1=ThisModel::whereIn('id',$update_data_contract_ids)->update(['moon_chao_status'=>1]);
//            $message_data['other_id']=$id;
//            $re=Message::add($message_data);
//            if($id && $re && $re1){
            if($id && $re1){
                $res=true;
                Db::commit();
            }
            else{
                Db::rollback();
            }
        } catch (\DomainException $e) {
            Db::rollback();
        }
        if(!$res){
            $this->del_rekey($keys);
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }

    /**
     * @brief   缴费
     * @author wanchengniuniu
     * @date 2025/2/28
     *
     * @param
     * @return
     */
    public function sendMessage()
    {
        $user = $this->auth->getUser();
        $user_id=$user->id;
        $keys=$this->get_keys('sendMessage'.$user_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
        //检测缴费记录
        $list=PaymentRecords::field('type,id,status,user_id')->where(['homeowner_id'=>$user_id,'status'=>PaymentRecords::STATUS_DEFAULT])->select();
        if(!is_null($list) && !is_array($list)){
            $list=$list->toArray();
        }
        if(!$list){
            $this->del_rekey($keys);
            $this->error('获取缴费信息失败');
        }
        //检测发送记录
        $user_ids=array_column($list,'user_id');
        $log_data=Message::where(['type'=>Message::TYPE_ONE])->whereIn('user_id',$user_ids)->select();
        $log_datas=[];
        if(!is_null($log_data) && !is_array($log_data)){
            $log_datas=$log_data->toArray();
        }
        if(!empty($log_datas)){
            $log_datas=array_column($log_datas,null,'other_id');
        }
        $insert_data=[];
        foreach ($list as $v){
            if(!isset($log_datas[$v['id']])){
                $insert_data[]=[
                    'type'=>Message::TYPE_ONE,
                    'user_id'=>$v['user_id'],
                    'other_id'=>$v['id'],
                    'title'=>'您有一条待缴费消息',
                    'content'=>'您有一条待缴费内容',
                ];
            }
        }
        if(!empty($insert_data)){
            (new Message())->insertAll($insert_data);
        }
        $this->success('提交成功',[]);
    }

    /**
     * @brief   缴费
     * @author wanchengniuniu
     * @date 2025/2/28
     */
    public function addOrder()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $user_id = $user->id;
        $keys = $this->get_keys('addOrder' . $user_id);
        if (!$this->check_repeat($keys, 3)) {
            $this->error('您点击的太快了');
        }
        $validate = new \app\api\validate\v2\Contract();
        $check_result = $validate->scene('addOrder')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        //检测缴费记录是否有效
        $info = PaymentRecords::where(['id' => $getData['pay_log_id'], 'user_id' => $user_id, 'status' => PaymentRecords::STATUS_DEFAULT])->find();
        if (!$info) {
            $this->del_rekey($keys);
            $this->error('获取缴费信息失败');
        }
        //检测是否已生成订单
        $order_info = OrderPaymentRecords::where(['other_id' => $info['id'], 'user_id' => $user_id])->order('updatetime desc')->find();
        $orderData = [];
        $end_time = time() - 1200;
        if (!$order_info) {
            //生成订单
            $orderData = [
                'order_sn' => create_order_sn('order_sn'),
                'pay_sn' => create_order_sn('pay_sn'),
                'other_id' => $info['id'],
                'money' => $info['money'],
                'user_id' => $user_id,
                'status' => OrderPaymentRecords::STATUS_DEFAULT,
                'createtime' => time(),
                'updatetime' => time(),
            ];
            $re = (new OrderPaymentRecords())->insert($orderData);
            if (!$re) {
                $this->del_rekey($keys);
                $this->error('下单失败');
            }
        } else {
            if ($order_info['status'] == OrderPaymentRecords::STATUS_NORMAL) {
                $this->del_rekey($keys);
                $this->error('订单已支付');
            }
            //更新支付单号
            $orderData = $order_info;
            $orderData['pay_sn'] = create_order_sn('pay_sn');
            $re = (new OrderPaymentRecords())
                ->where(['id' => $order_info['id']])
                ->update(['updatetime' => time(), 'pay_sn' => $orderData['pay_sn']]);
            if (!$re) {
                $this->del_rekey($keys);
                $this->error('下单失败');
            }

        }
        if (empty($orderData)) {
            $this->del_rekey($keys);
            $this->error('下单失败了');
        }
        //php71 think crud -t user_order_payment_records --relation=user --relation=user_payment_records --relationforeignkey=user_id --relationforeignkey=other_id
        //php71 think crud -t user_order_payment_records -d 1

        //吊起支付
        $goods_name = PaymentRecords::getTypeList(1, $info['type']);
        $goods_name .= '缴费';
        //回调链接
        $notifyurl = $this->request->root(true) . '/api/notify/pay_fees';
        $openid = $this->auth->openid;
        if (empty($openid)) $this->error('请先绑定小程序');
        $data = Service::submitOrder($orderData['money'], $orderData['pay_sn'], 'wechat', $goods_name, $notifyurl, '', 'miniapp', $openid);


//        $wxpay = new Wxpay();
//        $goods_name=PaymentRecords::getTypeList($info['type']);
//        $goods_name.='缴费';
//        $result = $wxpay->index($orderData['pay_sn'],$orderData['money'],$goods_name,$openid,config('site_url').'/api/notify/wx_order');
//        $result=json_decode($result,true);
        $this->success('提交成功', $data);
    }

    /**
     * 获取我的缴费列表
     */
    public function biaoLists()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 10);
            $contract_id = $this->request->param('contract_id/d', 0);
            $type = $this->request->param('type/d');//1=房租；2水电费

            if ($contract_id < 1) {
                $this->error('contract_id不能为空');
            }

            $user_id = $this->auth->id;
            $where = [
                'pr.type' => $type,
                'pr.user_id' => $user_id,
                'pr.contract_id' => $contract_id
            ];
            $Data = PaymentRecords::alias('pr')
                ->join('user_contract uc', 'uc.id=pr.contract_id', 'left')
                ->field('pr.id,pr.user_id,pr.status,pr.type,pr.money,pr.createtime,pr.updatetime,pr.relation_id,
                pr.money_electricity,pr.money_water,
                uc.start_time,uc.end_time')
                ->where($where)
                ->page($page, $limit)
                ->order('pr.status asc,pr.updatetime desc')
                ->select();
            foreach ($Data as $k => $item) {
                $item['status_text'] = PaymentRecords::getStatusList(1, $item['status']);
                $item['type_text'] = PaymentRecords::getTypeList(1, $item['type']);
                $item['createtime'] = date('Y-m-d H:i', $item['createtime']);
                $count = PaymentRecords::where([
                    'type' => $type,
                    'user_id' => $user_id,
                    'createtime' => ['<', $item['createtime']]
                ])->count();
                $count = $count + 1;

                $item['name_text'] = '第' . $count . '期';
                if ($type == 1) {
                    $time = $item['start_time'] . '至' . $item['end_time'];
                } else {
                    $startTime = date('Y.m.01', strtotime($item['createtime']));
                    $startTime1 = date('Y-m-01', strtotime($item['createtime']));
                    // 获取月末时间，这里先获取下一个月的月初，再减去1秒得到本月月末
                    $nextMonthStart = strtotime('+1 month', strtotime($startTime1));
                    $nextMonthStart = $nextMonthStart - 1;
                    $str = date('Y.m.d', $nextMonthStart);
                    $time = $startTime . '至' . $str;
                    $sub_type = 0;
                    if (!empty($item['money_water'])) {
                        $sub_type = 1;
                    } elseif (!empty($item['money_electricity'])) {
                        $sub_type = 2;
                    } elseif (!empty($item['other_fee'])) {
                        $sub_type = 3;
                    }

                    $item['sub_type'] = $sub_type;
                }
                $bill = BillModel::get($item->relation_id);
                $item['time'] = !empty($bill->period) ? $bill->period : $time;
                $Data[$k] = $item;
            }
            $this->success('查询成功', $Data);
        } else {
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取我的缴费详情
     */
    public function biaoDetail()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id/d', 0);
            $where = [
                'p.id' => $id,
                'p.user_id' => $this->auth->id
            ];

            $Data = PaymentRecords::alias('p')
                ->join('user_contract uc', 'uc.id=p.contract_id', 'left')
                ->field('uc.homeowner_name,uc.homeowner_phone,p.electricity_photo,p.water_photo,p.last_electricity_num,p.last_water_num,p.money_water as unit_money_water,p.money_electricity as unit_money_electricity,p.money_water,p.money_electricity,p.other_fee,p.water_num,p.electricity_num,p.contract_id,p.id,p.user_id,p.status,p.type,p.other_data,p.money,p.createtime,p.updatetime,uc.room_name,uc.build_address,uc.build_name')
                ->where($where);
            if (!empty($room_name)) {
                $Data->where('c.room_name', 'like', '%' . $room_name . '%');
            }
            $item = $Data->find();
            if (!$item) {
                $this->error('查询失败');
            }
            $item['water_photo'] = get_all_img_path($item['water_photo']);
            $item['electricity_photo'] = get_all_img_path($item['electricity_photo']);
            $item['water_photo_path'] = isset($item['water_photo'][0]) ? $item['water_photo'][0] : [];
            $item['electricity_photo_path'] = isset($item['electricity_photo'][0]) ? $item['electricity_photo'][0] : [];
            $item['status_text'] = PaymentRecords::getStatusList(1, $item['status']);
            $item['type_text'] = PaymentRecords::getTypeList(1, $item['type']);

            if ($item['type'] == PaymentRecords::TYPE_OTHER) {
                $money_data = [];
                if (!empty($item['money_electricity'])) {
                    $this_electricity_num = bcsub($item['electricity_num'], $item['last_electricity_num'], 2);
                    $money_data[] = [
                        'name' => '电费',
                        'num' => $this_electricity_num,
                        'price' => $item['unit_money_electricity'],
                        'money' => $item['money_electricity'],
                    ];
                }

                if (!empty($item['money_water'])) {
                    $this_water_num = bcsub($item['water_num'], $item['last_water_num'], 2);
                    $money_data[] = [
                        'name' => '水费',
                        'num' => $this_water_num,
                        'price' => $item['unit_money_water'],
                        'money' => $item['money_water'],
                    ];
                }

                if (!empty($item['other_data'])) {
                    $other_data = json_decode($item['other_data'], true);
                    foreach ($other_data as $vv) {
                        $money_data[] = [
                            'name' => $vv['name'],
                            'num' => 1,
                            'price' => $vv['money'],
                            'money' => $vv['money'],
                        ];
                    }
                }
            } else {
                $money_data = [
                    [
                        'name' => '房租',
                        'num' => '1',
                        'price' => $item['money'],
                        'money' => $item['money'],
                    ]
                ];
            }

            $item['total_money'] = $item['money'];
            $item['money_data'] = $money_data;
            $this->success('查询成功', $item);
        } else {
            $this->error('请求参数有误');
        }
    }


    /**
     * 获取我的已抄表列表
     */
    public function biaoHomeownerLists(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $page=isset($getData['page']) && !empty((int)$getData['page'])?(int)$getData['page']:1;
            $limit=isset($getData['limit']) && !empty((int)$getData['limit'])?(int)$getData['limit']:10;
            $room_name=isset($getData['keyword']) && !empty($getData['keyword'])?$getData['keyword']:'';
            $time=isset($getData['time']) && !empty($getData['time'])?$getData['time']:'';
            $where1=[];
            if(!empty($time)){
                $start_time = strtotime($time. '-01 00:00:00');
                $end_time = strtotime('last day of '. $time. '23:59:59');
                $where1="p.updatetime > ".$start_time.' and p.updatetime > '.$end_time;
            }
            $where = ['p.type'=>PaymentRecords::TYPE_OTHER
                ,'p.homeowner_id'=>$user_id
                ,'p.status'=>PaymentRecords::STATUS_DEFAULT];
            $Data = PaymentRecords::alias('p')
                ->join('user_contract uc','uc.id=p.contract_id')
                ->field('p.last_electricity_num,p.last_water_num,uc.money_water as unit_money_water,uc.money_electricity as unit_money_electricity,p.money_water,p.money_electricity,p.other_fee,p.water_num,p.electricity_num,p.contract_id,p.id,p.user_id,p.status,p.type,p.other_data,p.money,p.createtime,p.updatetime,uc.room_name,uc.build_address')->where($where)->where($where1);
            if (!empty($room_name)) {
                $Data->where('c.room_name', 'like', '%' . $room_name . '%');
            }
            $Data=$Data->page($page,$limit)
                ->order('p.status asc,p.updatetime desc')
                ->select();
            foreach ($Data as $k=>$item){
//                $item['water_photo']=explode(',',$item['water_photo']);
//                $item['water_photo_path']=isset($item['water_photo'][0])?$item['water_photo'][0]:[];
//                $item['electricity_photo']=explode(',',$item['electricity_photo']);
//                $item['electricity_photo_path']=isset($item['electricity_photo'][0])?$item['electricity_photo'][0]:[];
                $item['status_text']=PaymentRecords::getStatusList(1,$item['status']);
                $item['type_text']=PaymentRecords::getTypeList(1,$item['type']);
                $item['createtime']=date('Y-m-d H:i',$item['createtime']);
                $count=PaymentRecords::where(['type'=>PaymentRecords::TYPE_OTHER,'status'=>PaymentRecords::STATUS_DEFAULT])->where('createtime','<',$item['createtime'])->count();
                $count=bcadd($count,1);
                $item['name_text']='第'.$count.'期';
                if($item['type']==PaymentRecords::TYPE_OTHER){
                    $this_water_num=bcsub($item['water_num'],$item['last_water_num'],2);
                    $this_electricity_num=bcsub($item['electricity_num'],$item['last_electricity_num'],2);
                    $money_data=[
                        [
                            'name'=>'电费',
                            'num'=>$this_electricity_num,
                            'price'=>$item['unit_money_electricity'],
                            'money'=>$item['money_electricity'],
                        ],
                        [
                            'name'=>'水费',
                            'num'=>$this_water_num,
                            'price'=>$item['unit_money_water'],
                            'money'=>$item['money_water'],
                        ]
                    ];
                    if(!empty($item['other_data'])){
                        $other_data=json_decode($item['other_data'],true);
                        foreach ($other_data as $vv){
                            $money_data[]=[
                                'name'=>$vv['name'],
                                'num'=>1,
                                'price'=>$vv['money'],
                                'money'=>$vv['money'],
                            ];
                        }
                    }
                }
                else{
                    $money_data=[
                        [
                            'name'=>'房租',
                            'num'=>'1',
                            'price'=>$item['money'],
                            'money'=>$item['money'],
                        ]
                    ];
                }

                $item['total_money']=$item['money'];
                $item['money_data']=$money_data;
                $Data[$k]=$item;
            }
            $this->success('查询成功',$Data);
        }else{
            $this->error('请求参数有误');
        }
    }
    /**
     * 获取我的已抄表列表
     */
    public function biaoHomeownerListsNew(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $page=isset($getData['page']) && !empty((int)$getData['page'])?(int)$getData['page']:1;
            $limit=isset($getData['limit']) && !empty((int)$getData['limit'])?(int)$getData['limit']:10;

//            $where = ['type'=>PaymentRecords::TYPE_OTHER,'homeowner_id'=>$user_id,'status'=>PaymentRecords::STATUS_DEFAULT];
            $where = ['type'=>PaymentRecords::TYPE_OTHER,'homeowner_id'=>$user_id,'status'=>PaymentRecords::STATUS_DEFAULT];
            $Data=ThisModel::alias('c')
                ->join('building b','b.id=c.build_id')
                ->field('count(*) as total,b.address as build_name,b.images as build_image')
                ->where(['c.moon_chao_status'=>1])
                ->group('build_id')
                ->select();
            foreach ($Data as $k=>$item){
                $item['tag']=[
                    '电表',
                    '水表',
                    '物业费',
                ];
                $item['build_image']=!empty($item['build_image'])?get_all_img_paths($item['build_image']):[];

//                $item['build_image']=get_img_path($item['build_image']);
                $Data[$k]=$item;
            }
            $this->success('查询成功',$Data);
        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取楼栋未抄表详情列表
     */
    public function biaoBuildWeiInfoLists(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $page=isset($getData['page']) && !empty((int)$getData['page'])?(int)$getData['page']:1;
            $limit=isset($getData['limit']) && !empty((int)$getData['limit'])?(int)$getData['limit']:10;
            $build_id=isset($getData['build_id']) && !empty((int)$getData['build_id'])?(int)$getData['build_id']:0;
            $room_name=isset($getData['room_name']) && !empty($getData['room_name'])?$getData['room_name']:'';
            if(!$build_id){
                $this->error('请求参数有误');
            }

            $where = ['c.build_id'=>$build_id
                ,'c.homeowner_id'=>$user_id
                ,'c.moon_chao_status'=>0];
//            $where1='';
//            if(!empty($room_name)){
//                $where1='c.room_name like %'.$room_name.'%';
//            }
            $Data=ThisModel::alias('c')
                ->join('building b','b.id=c.build_id')
                ->field('c.id,c.house_id,c.room_name,b.address as build_name,c.water_num as last_water_num,c.electricity_num as last_electricity_num,moon_chao_status')
                ->where($where);
//                ->where($where1);
            if (!empty($room_name)) {
                $Data->where('c.room_name', 'like', '%' . $room_name . '%');
            }

            $Data = $Data->page($page, $limit)
                ->select();
            $address='';
            foreach ($Data as $k=>$item){
                $address=$item['build_name'];
                if($item['moon_chao_status']){
                    //查询历史抄表数据
                    $info=PaymentRecords::where(['contract_id'=>$item['id']])->order('updatetime','desc')->find();
                    if($info){
                        $item['last_water_num']=$info['last_water_num'];
                        $item['last_electricity_num']=$info['last_electricity_num'];
                    }
                }
                $Data[$k]=$item;
            }
            $this->success('查询成功',$Data);
        }else{
            $this->error('请求参数有误');
        }
    }
    /**
     * 获取我的未抄表列表
     */
    public function biaoWeiBuildLists(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $page=isset($getData['page']) && !empty((int)$getData['page'])?(int)$getData['page']:1;
            $limit=isset($getData['limit']) && !empty((int)$getData['limit'])?(int)$getData['limit']:10;

            $where = ['type'=>PaymentRecords::TYPE_OTHER
                ,'homeowner_id'=>$user_id
                ,'status'=>PaymentRecords::STATUS_DEFAULT];
            $Data=ThisModel::alias('c')
                ->join('building b','b.id=c.build_id')
                ->field('count(*) as total,b.address as build_name,b.images as build_image,build_id')
                ->where(['c.moon_chao_status'=>0])
                ->group('build_id')
                ->page($page,$limit)
                ->select();
            foreach ($Data as $k=>$item){
                $item['tag']=[
                    '电表',
                    '水表',
                    '物业费',
                ];
                $item['build_image']=!empty($item['build_image'])?get_all_img_paths($item['build_image']):[];

//                $item['build_image']=get_img_path($item['build_image']);
                $Data[$k]=$item;
            }
            $this->success('查询成功',$Data);
        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取我的已抄表详情
     */
    public function biaoHomeownerInfo(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $id=isset($getData['id']) && !empty((int)$getData['id'])?(int)$getData['id']:0;
            if(!$id){
                $this->error('参数错误');
            }

            $where = ['p.id'=>$id
                ,'p.type'=>PaymentRecords::TYPE_OTHER
                ,'p.homeowner_id'=>$user_id
            ];

            $item = PaymentRecords::alias('p')
                ->join('user_contract uc','uc.id=p.contract_id')
                ->field('p.water_photo,p.electricity_photo,p.last_electricity_num,p.last_water_num,p.money_water as unit_money_water,p.money_electricity as unit_money_electricity,p.money_water,p.money_electricity,p.other_fee,p.water_num,p.electricity_num,p.contract_id,p.id,p.user_id,p.status,p.type,p.other_data,p.money,p.createtime,p.updatetime,uc.room_name,uc.build_address')
                ->where($where)
            ->find();
            if(!$item){
                $this->error('获取失败');
            }
            $item['status_text']=PaymentRecords::getStatusList(1,$item['status']);
            $item['water_photo']=get_all_img_path($item['water_photo']);
            $item['electricity_photo']=get_all_img_path($item['electricity_photo']);
            $item['type_text']=PaymentRecords::getTypeList(1,$item['type']);
            $count=PaymentRecords::where(['id'=>$id,'type'=>PaymentRecords::TYPE_OTHER])->where('createtime','<',$item['createtime'])->count();

            $item['createtime']=date('Y-m-d',$item['createtime']);
            $count=bcadd($count,1);
            $item['name_text']='第'.$count.'期';
            if($item['type']==PaymentRecords::TYPE_OTHER){
                $this_water_num=bcsub($item['water_num'],$item['last_water_num'],2);
                $this_electricity_num=bcsub($item['electricity_num'],$item['last_electricity_num'],2);
                $money_data=[
                    [
                        'name'=>'电费',
                        'num'=>$this_electricity_num,
                        'price'=>$item['unit_money_electricity'],
                        'money'=>$item['money_electricity'],
                    ],
                    [
                        'name'=>'水费',
                        'num'=>$this_water_num,
                        'price'=>$item['unit_money_water'],
                        'money'=>$item['money_water'],
                    ]
                ];
                if(!empty($item['other_data'])){
                    $other_data=json_decode($item['other_data'],true);
                    foreach ($other_data as $vv){
                        $money_data[]=[
                            'name'=>$vv['name'],
                            'num'=>1,
                            'price'=>$vv['money'],
                            'money'=>$vv['money'],
                        ];
                    }
                }
            }
            else{
                $money_data=[
                    [
                        'name'=>'房租',
                        'num'=>'1',
                        'price'=>$item['money'],
                        'money'=>$item['money'],
                    ]
                ];
            }

            $item['total_money']=$item['money'];
            $item['money_data']=$money_data;
            $this->success('查询成功',$item);
        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * @brief   修改抄表
     * @author wanchengniuniu
     * @date 2025/3/1
     *
     * @param
     * @return
     */
    public function editBiao()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $homeowner_id=$user->id;
        $keys=$this->get_keys('addBiao'.$homeowner_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
        $validate=new \app\api\validate\v2\Contract();
        $check_result=$validate->scene('editBiao')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        //检测缴费是否有效
        $info=PaymentRecords::alias('p')
            ->join('user_contract uc','uc.id=p.contract_id')
            ->field('p.*,uc.money_electricity as unit_money_electricity,uc.money_water as unit_money_water')
            ->where(['p.id'=>$getData['pay_log_id'],'p.homeowner_id'=>$homeowner_id])->find();
        if(!$info){
            $this->del_rekey($keys);
            $this->error('获取缴费信息失败');
        }
        if($info['status']!=PaymentRecords::STATUS_DEFAULT){
            $this->del_rekey($keys);
            $this->error('缴费状态异常');
        }

        if (!empty($getData['water_photo'])) {
            $photos=explode(',',$getData['water_photo']);
            foreach ($photos as $v){
                $ext_arr=explode('.',$v);
                if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg'])){
                    $this->del_rekey($keys);
                    $this->error('图片格式错误');
                }
                $this_data=['water_photo'=>$v];
                $check_result=$validate->scene('addBiao_water_photo')->check($this_data);
                if (!$check_result) {
                    $this->del_rekey($keys);
                    $this->error($validate->getError());
                }
            }
        }
        if (!empty($getData['electricity_photo'])) {
            $photos=explode(',',$getData['electricity_photo']);
            foreach ($photos as $v){
                $ext_arr=explode('.',$v);
                if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg'])){
                    $this->del_rekey($keys);
                    $this->error('图片格式错误');
                }
                $this_data=['electricity_photo'=>$v];
                $check_result=$validate->scene('addBiao_electricity_photo')->check($this_data);
                if (!$check_result) {
                    $this->del_rekey($keys);
                    $this->error($validate->getError());
                }
            }
        }
        $insert_data['last_water_num']=$info['last_water_num'];
        $insert_data['last_electricity_num']=$info['last_electricity_num'];
        $this_water=bcsub($getData['water_num'],$insert_data['last_water_num'],2);
        $this_electricity=bcsub($getData['electricity_num'],$insert_data['last_electricity_num'],2);
        if($this_water<0){
            $this->del_rekey($keys);
            $this->error('水表参数异常');
        }
        if($this_electricity<0){
            $this->del_rekey($keys);
            $this->error('电表参数异常');
        }
        $money_electricity=bcmul($this_electricity,$info['unit_money_electricity'],2);
        $money_water=bcmul($this_water,$info['unit_money_water'],2);
        $money=bcadd($money_water,$money_electricity,2);
        $other_data=json_decode(html_entity_decode($getData['other_data']),true);
        $other_fee=0;
        foreach ($other_data as $v){
            $other_fee+=$v['money'];
        }
        $insert_data=[
            'homeowner_id'=>$homeowner_id,
            'user_id'=>$info['user_id'],
            'type'=>PaymentRecords::TYPE_OTHER,
            'water_photo'=>$getData['water_photo'],
            'electricity_photo'=>$getData['electricity_photo'],
            'other_fee'=>$other_fee,
            'other_data'=>json_encode($other_data),
            'water_num'=>$getData['water_num'],
            'status'=>PaymentRecords::STATUS_DEFAULT,
            'electricity_num'=>$getData['electricity_num'],
        ];

        $money=bcadd($money,$insert_data['other_fee'],2);
        $insert_data['money_electricity']=$money_electricity;
        $insert_data['money_water']=$money_water;
        $insert_data['money']=$money;
        $insert_data['updatetime']=time();

//        $message_data=[
//            'type'=>Message::TYPE_ONE,
//            'user_id'=>$insert_data['user_id'],
//            'title'=>'您有一条待缴费修改消息',
//            'content'=>'您有一条待缴费修改内容',
//        ];
        $res=false;
        try{
            Db::startTrans();
            //推送缴费消息
            $id=(new PaymentRecords())->where(['id'=>$info['id']])->update($insert_data);
//            $message_data['other_id']=$info['id'];
//            $re=Message::add($message_data);
//            if($id && $re){
            if($id){
                $res=true;
                Db::commit();
            }
            else{
                Db::rollback();
            }
        } catch (\DomainException $e) {
            Db::rollback();
        }
        if(!$res){
            $this->del_rekey($keys);
            $this->error('提交失败');
        }
        $this->success('提交成功');
    }

    /**
     * @brief   通知租客缴费(发消息)
     * @author wanchengniuniu
     * @date 2025/3/1
     *
     * @param
     * @return
     */
    public function sendBiaoMessage()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $homeowner_id=$user->id;
        $keys=$this->get_keys('addBiao'.$homeowner_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
        $validate=new \app\api\validate\v2\Contract();
        $check_result=$validate->scene('sendBiaoMessage')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }
        //检测合同是否有效
        $where=[
            'id'=>$getData['pay_log_id']
//            ,'homeowner_id'=>$homeowner_id
];
        $info=PaymentRecords::where($where)->find();
        if(!$info){
            $this->del_rekey($keys);
            $this->error('获取缴费信息失败');
        }
        if($info['status']!=PaymentRecords::STATUS_DEFAULT){
            $this->del_rekey($keys);
            $this->error('缴费状态异常');
        }

        $message_data=[
            'type'=>Message::TYPE_ONE,
            'user_id'=>$info['user_id'],
            'other_id'=>$info['id'],
        ];
        if(Message::where($message_data)->find()){
            $this->success('发送成功');
        }
        $message_data['title']='您有一条待缴费修改消息';
        $message_data['content']='您有一条待缴费修改内容';
        $res=false;
        try{
            Db::startTrans();
            $re=Message::add($message_data);
            if($re){
                $res=true;
                Db::commit();
            }else{
                Db::rollback();
            }
        } catch (\DomainException $e) {
            Db::rollback();
        }
        if(!$res){
            $this->del_rekey($keys);
            $this->error('提交失败');
        }
        $this->success('发送成功');
    }

    /**
     * @brief   报修
     * @author wanchengniuniu
     * @date 2025/3/3
     *
     * @param
     * @return
     */
    public function sendHouseError()
    {
        $user = $this->auth->getUser();
        $getData = $this->request->post();
        $user_id=$user->id;
        $keys=$this->get_keys('sendHouseError'.$user_id);
        if (!$this->check_repeat($keys,3)) {
            $this->error('您点击的太快了');
        }
//        $path=Env::get('root_path');
//        file_put_contents($path.'/public/logs_error.log','time:'.date('Y-m-d H:i:s').json_encode($getData).PHP_EOL,FILE_APPEND);

        $validate=new \app\api\validate\v2\Contract();
        $check_result=$validate->scene('sendHouseError')->check($getData);
        if (!$check_result) {
            $this->del_rekey($keys);
            $this->error($validate->getError());
        }

        //检测合同是否有效
        $info=ThisModel::where(['room_id'=>(int)$getData['room_id'],'status'=>ThisModel::STATUS_NORMAL])->find();
        if(!$info){
            $this->del_rekey($keys);
            $this->error('合同异常');
        }
        if (!empty($getData['error_photo'])) {
            $photos=explode(',',$getData['error_photo']);
            foreach ($photos as $v){
                $ext_arr=explode('.',$v);
                if(!in_array($ext_arr[count($ext_arr)-1],['png','jpeg','jpg'])){
                    $this->del_rekey($keys);
                    $this->error('图片格式错误');
                }
                $this_data=['error_photo'=>$v];
                $check_result=$validate->scene('sendHouseError_error_photo')->check($this_data);
                if (!$check_result) {
                    $this->del_rekey($keys);
                    $this->error($validate->getError());
                }
            }
        }
        $insert_data=[
            'user_id'=>$user_id,
            'contract_id'=>$info['id'],
            'homeowner_id'=>$info['homeowner_id'],
            'status'=>ContractError::STATUS_DEFAULT,
            'type'=>$getData['error_type'],
            'photo'=>$getData['error_photo'],
            'title'=>$getData['error_title'],
        ];
        $re=ContractError::where($insert_data)->find();
        if($re){
            $this->error('重复提交');
        }
        $insert_data['createtime']=time();
        $insert_data['updatetime']=time();
        $message_data=[
            'type'=>Message::TYPE_THREE,
            'user_id'=>$info['homeowner_id'],
            'title'=>'您有一条待查看报修消息',
            'content'=>'您有一条待查看报修内容',
        ];
        //php71 think crud -t user_contract_error --relation=user --relation=user --relation=user_contract --relationforeignkey=user_id --relationforeignkey=homeowner_id --relationforeignkey=contract_id --imagefield=photo
        //php71 think crud -t user_contract_error -d 1
        $res=false;
        try{
            Db::startTrans();
            $id=(new ContractError())->insertGetId($insert_data);
            $message_data['other_id']=$id;
            $re=Message::add($message_data);
            if($re && $id){
                $res=true;
                Db::commit();
            }else{
                Db::rollback();
            }
        } catch (\Exception $e) {
            Db::rollback();
        }
        if(!$res){
            $this->del_rekey($keys);
            $this->error('提交失败');
        }
        $this->success('报修成功');
    }

    /**
     * @brief   获取报修类型
     * @author wanchengniuniu
     * @date 2025/3/3
     *
     * @param
     * @return
     */
    public function getHouseErrorType()
    {
        $list=ContractError::getTypeList();
        $this->success('获取成功',$list);
    }

    /**
     * 获取我的报修列表（用户）
     */
    public function baoUserLists(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $page=isset($getData['page']) && !empty((int)$getData['page'])?(int)$getData['page']:1;
            $limit=isset($getData['limit']) && !empty((int)$getData['limit'])?(int)$getData['limit']:10;
            $where = ['user_id'=>$user_id];
            $Data = ContractError::field('id,title,user_id,status,type,createtime,updatetime')->where($where)
                ->page($page,$limit)
                ->order('status asc,updatetime desc')
                ->select();
            foreach ($Data as $k=>$item){
//                $item['water_photo']=explode(',',$item['water_photo']);
//                $item['water_photo_path']=isset($item['water_photo'][0])?$item['water_photo'][0]:[];
//                $item['electricity_photo']=explode(',',$item['electricity_photo']);
//                $item['electricity_photo_path']=isset($item['electricity_photo'][0])?$item['electricity_photo'][0]:[];
                $item['status_text']=ContractError::getStatusList(1,$item['status']);
                $item['type_text']=ContractError::getTypeList(1,$item['type']);
                $item['createtime']=date('Y-m-d H:i',$item['createtime']);
                $Data[$k]=$item;
            }
            $this->success('查询成功',$Data);
        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取我的报修列表（房东）
     */
    public function baoLists(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $page=isset($getData['page']) && !empty((int)$getData['page'])?(int)$getData['page']:1;
            $limit=isset($getData['limit']) && !empty((int)$getData['limit'])?(int)$getData['limit']:10;
            $where = ['homeowner_id'=>$user_id];
            $Data = ContractError::field('id,user_id,title,status,type,createtime,updatetime')->where($where)
                ->page($page,$limit)
                ->order('status asc,updatetime desc')
                ->select();
            foreach ($Data as $k=>$item){
//                $item['water_photo']=explode(',',$item['water_photo']);
//                $item['water_photo_path']=isset($item['water_photo'][0])?$item['water_photo'][0]:[];
//                $item['electricity_photo']=explode(',',$item['electricity_photo']);
//                $item['electricity_photo_path']=isset($item['electricity_photo'][0])?$item['electricity_photo'][0]:[];
                $item['status_text']=ContractError::getStatusList(1,$item['status']);
                $item['type_text']=ContractError::getTypeList(1,$item['type']);
                $item['createtime']=date('Y-m-d H:i',$item['createtime']);
                $Data[$k]=$item;
            }
            $this->success('查询成功',$Data);
        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取我的报修详情（房东）
     */
    public function baoDetail(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $id=isset($getData['id']) && !empty((int)$getData['id'])?(int)$getData['id']:0;
            $where = [
//                'homeowner_id'=>$user_id,
                'id'=>$id];
            $item = ContractError::field('deletetime',true)->where($where)
                ->order('status asc,updatetime desc')
                ->find();
            if(!$item){
                $this->error('获取失败');
            }
            $item['status_text']=ContractError::getStatusList(1,$item['status']);
            $item['type_text']=ContractError::getTypeList(1,$item['type']);
            $item['createtime']=date('Y-m-d H:i',$item['createtime']);
            $item['updatetime']=date('Y-m-d H:i',$item['updatetime']);
            $contract_info=\app\common\model\Contract::where(['id'=>$item['contract_id']])->find();
            $item['build_address']=$contract_info['build_address'];
            $item['room_name']=$contract_info['room_name'];
            $item['homeowner_name']=$contract_info['homeowner_name'];
            $item['homeowner_phone']=$contract_info['homeowner_phone'];

            $this->success('查询成功',$item);
        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取我的报修详情（用户）
     */
    public function baoUserDetail(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $id=isset($getData['id']) && !empty((int)$getData['id'])?(int)$getData['id']:0;
            $where = [
                'user_id'=>$user_id,
                'id'=>$id];
            $item = ContractError::field('deletetime',true)->where($where)
                ->order('status asc,updatetime desc')
                ->find();
            $item['status_text']=ContractError::getStatusList(1,$item['status']);
            $item['type_text']=ContractError::getTypeList(1,$item['type']);
            $item['createtime']=date('Y-m-d H:i',$item['createtime']);
            $item['updatetime']=date('Y-m-d H:i',$item['updatetime']);
            $this->success('查询成功',$item);
        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * @brief   线下缴费
     * @author wanchengniuniu
     * @date 2025/3/3
     *
     * @param
     * @return
     */
    public function offlinePayment()
    {
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $homeowner_id=$user->id;
            $keys=$this->get_keys('offlinePayment'.$homeowner_id);
            if (!$this->check_repeat($keys,3)) {
                $this->error('您点击的太快了');
            }
            $validate=new \app\api\validate\v2\Contract();
            $check_result=$validate->scene('offlinePayment')->check($getData);
            if (!$check_result) {
                $this->del_rekey($keys);
                $this->error($validate->getError());
            }
            //检测缴费是否有效
            $info=PaymentRecords::where(['id'=>$getData['pay_log_id'],'homeowner_id'=>$homeowner_id])->find();
            if(!$info){
                $this->del_rekey($keys);
                $this->error('获取缴费信息失败');
            }
            if($info['status']!=PaymentRecords::STATUS_DEFAULT){
                $this->del_rekey($keys);
                $this->error('缴费状态异常');
            }

            //检测是否有线下缴费订单
            $order_info=OrderPaymentRecords::where(['other_id'=>$info['id']])->find();
            $create_data=[];
            if($order_info){
                //检测订单是否已支付
                if($order_info['status']==1){
                    $this->error('记录已支付');
                }
            }
            else{
                //创建订单
                $create_data=[
                    'order_sn'=>create_order_sn('order_sn'),
                    'pay_sn'=>create_order_sn('pay_sn'),
                    'other_id'=>$info['id'],
                    'money'=>$info['money'],
                    'user_id'=>$info['user_id'],
                    'status'=>OrderPaymentRecords::STATUS_NORMAL,
                    'pay_type'=>OrderPaymentRecords::PAY_TYPE_OFFLINE,
                    'createtime'=>time(),
                    'updatetime'=>time(),
                ];
            }
            $message_data=[
                'type'=>Message::TYPE_ONE,
                'user_id'=>$info['homeowner_id'],
                'title'=>'您有一条待查看缴费消息',
                'content'=>'您有一条缴费状态已改变',
            ];
            $res=false;
            try{
                Db::startTrans();
                //推送缴费消息
                $re=(new PaymentRecords())->where(['id'=>$info['id']])->update(['updatetime'=>time(),'status'=>PaymentRecords::STATUS_NORMAL]);
                //处理订单
                if(!empty($create_data)){
                    $re1=(new OrderPaymentRecords())->insert($create_data);
                }else{
                    $re1=(new OrderPaymentRecords())->where(['id'=>$order_info['id']])->update(['updatetime'=>time(),'status'=>OrderPaymentRecords::STATUS_NORMAL,'pay_type'=>OrderPaymentRecords::PAY_TYPE_OFFLINE]);
                }
                $message_data['other_id']=$info['id'];
                $re2=Message::add($message_data);
                if($re && $re2 && $re1){
                    $res=true;
                    Db::commit();
                }
                else{
                    Db::rollback();
                }
            } catch (\DomainException $e) {
                Db::rollback();
            }
            if(!$res){
                $this->del_rekey($keys);
                $this->error('缴费失败');
            }
            $this->success('缴费成功');
        }else{
            $this->error('请求参数有误');
        }
    }


    /**
     * 获取本月收租账单
     */
    public function billLists(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $page=isset($getData['page']) && !empty((int)$getData['page'])?(int)$getData['page']:1;
            $limit=isset($getData['limit']) && !empty((int)$getData['limit'])?(int)$getData['limit']:10;
            $room_name=isset($getData['keyword']) && !empty($getData['keyword'])?$getData['keyword']:'';
            $where = [
                'p.homeowner_id'=>$user_id,
                'p.type'=>PaymentRecords::TYPE_FANG];
            $where1 = '';
            $building=isset($getData['building']) && !empty((int)$getData['building'])?(int)$getData['building']:0;
            if($building){
                //加入楼栋搜索条件
                $where['c.build_id'] = $building;
            }
            $time=isset($getData['time']) && !empty($getData['time'])?$getData['time']:'';
            $startTime = strtotime($time . '-01 00:00:00');
            if(!empty($time)){
                if(strtotime(date('Y-m',strtotime($time)))!=strtotime($time)){
                    $this->error('时间格式错误');
                }
                // 获取该月的开始时间（即该月 1 号 00:00:00）
                // 获取该月的结束时间（即该月最后一天 23:59:59）
                $endTime = strtotime('last day of ' . $time . ' 23:59:59');
                // 将时间戳格式化为日期时间字符串
//                $startDateTime = date('Y-m-d H:i:s', $startTime);
//                $endDateTime = date('Y-m-d H:i:s', $endTime);
                $where1 = "createtime between '{$startTime}' and '{$endTime}'";
            }else{
                $where1 = "createtime < '{$startTime}'";
            }
//            $where1=['homeowner_id'=>$user_id];
            $where2=[];
            $total_re=PaymentRecords::field('money,status')->where($where2)->where($where1)->select();
            if(!is_null($total_re) &&!is_array($total_re)){
                $total_re=$total_re->toArray();
            }
            $default_money=0;
            $total_money=0;
            $normal_money=0;
            foreach ($total_re as $v){
                if($v['status']==PaymentRecords::STATUS_DEFAULT){
                    $default_money=bcadd($default_money,$v['money'],2);
                }
                if($v['status']==PaymentRecords::STATUS_NORMAL){
                    $normal_money=bcadd($normal_money,$v['money'],2);
                }
                $total_money=bcadd($normal_money,$v['money'],2);
            }
            $total_data=[
                'total_money'=>$total_money,
                'yi_money'=>$normal_money,
                'wei_money'=>$default_money,
            ];
            if(!empty($where1)){
                $where1='p.'.$where1;
            }
            //状态：传空或0默认为全部1待收款2已收入3已逾期4已退款
            $status=isset($getData['status']) && !empty((int)$getData['status'])?(int)$getData['status']:0;
            if($status){
                if($status==1){
                    $where['p.status'] = PaymentRecords::STATUS_DEFAULT;
                }
                if($status==2){
                    $where['p.status'] = PaymentRecords::STATUS_NORMAL;
                }
                if($status==3){
                    $where['p.status'] = PaymentRecords::STATUS_DEFAULT;
                    //待确定时间
//                    $where1 = 'createtime < ';
                }
                if($status==4){
//                    $where['status'] = PaymentRecords::STATUS_DEFAULT;
//                    $where1 = 'createtime < ';
                }
            }

            $Data = PaymentRecords::alias('p')
                ->join('user_contract c','c.id=p.contract_id')
                ->join('user u','u.id=p.user_id')
                ->field('p.id,p.user_id,p.status,p.type,p.money,p.createtime,p.updatetime,c.build_address,c.room_name,c.build_address,u.nickname,c.room_name,c.build_address')
                ->where($where)->where($where1);
            if (!empty($room_name)) {
                $Data->where('c.room_name', 'like', '%' . $room_name . '%');
            }
            $Data=$Data->page($page,$limit)
                ->order('p.status asc,p.updatetime desc')
                ->select();
            foreach ($Data as $k=>$item){
                $item['status_text']=PaymentRecords::getStatusList(1,$item['status']);
                $item['type_text']=PaymentRecords::getTypeList(1,$item['type']);
                $item['createtime']=date('Y-m-d H:i',$item['createtime']);
                $Data[$k]=$item;
            }
            $re_data=[
                'data'=>$Data,
                'total'=>$total_data,
            ];
            $this->success('查询成功',$re_data);
        }else{
            $this->error('请求参数有误');
        }
    }

    /**
     * 获取本月收租账单详情
     */
    public function billInfo(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $id=isset($getData['id']) && !empty((int)$getData['id'])?(int)$getData['id']:0;
            if(!$id){
                $this->error('请求参数有误');
            }
            $where=['p.id'=>$id
                ,'p.homeowner_id'=>$user_id
            ];
            $item = PaymentRecords::alias('p')
                ->join('user_contract uc','uc.id=p.contract_id')
                ->join('user u','u.id=p.user_id')
                ->field('p.last_electricity_num,p.last_water_num,p.money_water as unit_money_water,p.money_electricity as unit_money_electricity,p.money_water,p.money_electricity,p.other_fee,p.water_num,p.electricity_num,p.contract_id,p.id,p.user_id,p.status,p.type,p.other_data,p.money,p.createtime,p.updatetime,uc.room_name,uc.build_address')
                ->where($where)
                ->find();
            if(!$item){
                $this->error('获取失败');
            }
            $item['status_text']=PaymentRecords::getStatusList(1,$item['status']);
            $item['type_text']=PaymentRecords::getTypeList(1,$item['type']);
            $item['createtime']=date('Y-m-d H:i',$item['createtime']);
            if($item['type']==PaymentRecords::TYPE_OTHER){
                $this_water_num=bcsub($item['water_num'],$item['last_water_num'],2);
                $this_electricity_num=bcsub($item['electricity_num'],$item['last_electricity_num'],2);
                $money_data=[
                    [
                        'name'=>'电费',
                        'num'=>$this_electricity_num,
                        'price'=>$item['unit_money_electricity'],
                        'money'=>$item['money_electricity'],
                    ],
                    [
                        'name'=>'水费',
                        'num'=>$this_water_num,
                        'price'=>$item['unit_money_water'],
                        'money'=>$item['money_water'],
                    ]
                ];
                if(!empty($item['other_data'])){
                    $other_data=json_decode($item['other_data'],true);
                    foreach ($other_data as $vv){
                        $money_data[]=[
                            'name'=>$vv['name'],
                            'num'=>1,
                            'price'=>$vv['money'],
                            'money'=>$vv['money'],
                        ];
                    }
                }
            }
            else{
                $money_data=[
                    [
                        'name'=>'房租',
                        'num'=>'1',
                        'price'=>$item['money'],
                        'money'=>$item['money'],
                    ]
                ];
            }

            $item['total_money']=$item['money'];
            $item['money_data']=$money_data;
            $this->success('查询成功',$item);
        }else{
            $this->error('请求参数有误');
        }
    }
    public function billListsOld(){
        if($this->request->isPost()){
            $user = $this->auth->getUser();
            $getData = $this->request->post();
            $user_id=$user->id;
            $page=isset($getData['page']) && !empty((int)$getData['page'])?(int)$getData['page']:1;
            $limit=isset($getData['limit']) && !empty((int)$getData['limit'])?(int)$getData['limit']:10;
            $where = ['homeowner_id'=>$user_id];
            $where1 = '';
            $building=isset($getData['building']) && !empty((int)$getData['building'])?(int)$getData['building']:0;
            if($building){
                //加入楼栋搜索条件
            }
            $time=isset($getData['time']) && !empty($getData['time'])?$getData['time']:'';
            if(!empty($time)){
                if(strtotime(date('Y-m',strtotime($time)))!=strtotime($time)){
                    $this->error('时间格式错误');
                }
                // 获取该月的开始时间（即该月 1 号 00:00:00）
                $startTime = strtotime($time . '-01 00:00:00');
                // 获取该月的结束时间（即该月最后一天 23:59:59）
                $endTime = strtotime('last day of ' . $time . ' 23:59:59');
                // 将时间戳格式化为日期时间字符串
                $startDateTime = date('Y-m-d H:i:s', $startTime);
                $endDateTime = date('Y-m-d H:i:s', $endTime);
                $where1 = "createtime between '{$startTime}' and '{$endTime}'";
            }
            //状态：传空或0默认为全部1待收款2已收入3已逾期4已退款
            $status=isset($getData['status']) && !empty((int)$getData['status'])?(int)$getData['status']:0;
            if($status){
                if($status==1){
                    $where['status'] = PaymentRecords::STATUS_DEFAULT;
                }
                if($status==2){
                    $where['status'] = PaymentRecords::STATUS_NORMAL;
                }
                if($status==3){
                    $where['status'] = PaymentRecords::STATUS_DEFAULT;
                    //待确定时间
//                    $where1 = 'createtime < ';
                }
                if($status==4){
//                    $where['status'] = PaymentRecords::STATUS_DEFAULT;
//                    $where1 = 'createtime < ';
                }
            }

            $Data = PaymentRecords::field('id,user_id,status,type,money,createtime,updatetime')
                ->where($where)->where($where1)
                ->page($page,$limit)
                ->order('status asc,updatetime desc')
                ->select();
            foreach ($Data as $k=>$item){
                $item['status_text']=PaymentRecords::getStatusList(1,$item['status']);
                $item['type_text']=PaymentRecords::getTypeList(1,$item['type']);
                $item['createtime']=date('Y-m-d H:i',$item['createtime']);
                $Data[$k]=$item;
            }
            $this->success('查询成功',$Data);
        }else{
            $this->error('请求参数有误');
        }
    }

}
